<?php


namespace App\W7OpenTracing;


use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use const OpenTracing\Formats\TEXT_MAP;

class Carrier
{
    public static function fromRequest($request = null): array
    {
        $request = $request ?? \request();
        if ($request instanceof \Illuminate\Http\Request) {
            $headers = \request()->headers;
            $carrier = [];
            foreach ($headers->getIterator() as $key => $values) {
                if (Str::startsWith($key, 'x-b3-') && count($values) === 1) {
                    $carrier[$key] = Arr::get($values, 0, '');
                }
            }
            return $carrier;
        }
        throw new \InvalidArgumentException('invalid request');
    }

    public static function fromSpan(\OpenTracing\Span $span): array
    {
        return self::fromSpanContext($span->getContext());
    }

    public static function fromSpanContext(\OpenTracing\SpanContext $spanContext): array
    {
        $tracer = Facade::tracer();

        $carrier = [];
        $tracer->inject($spanContext, TEXT_MAP, $carrier);

        return $carrier;
    }
}
